import {iMicroAppPageButtonRefer} from "./MicroApp.pageButton";
import {computed, inject, onBeforeUnmount, provide, reactive} from "@peryl/react-compose";
import {iMicroAppPageConfig, iMicroAppPageConfigProcessor} from "@peryl/micro-web";
import {remove} from "@peryl/utils/remove";

/**
 * 页面配置控制模块
 * @author  韦胜健
 * @date    2024.6.12 22:38
 */
export const MicroAppPageConfig = (() => {

  const PROVIDE_NAME = '@@MicroAppPageConfig';

  const useProvider = (pageButtonRefer: iMicroAppPageButtonRefer, isFirstPage: boolean) => {

    const state = reactive({
      pageConfigProcessor: [] as iMicroAppPageConfigProcessor[]
    });

    const pageConfig = computed(() => {
      const ret: iMicroAppPageConfig = {
        title: '',
        showBackButton: !isFirstPage,
        hideNavigation: false,
        buttons: pageButtonRefer.showButtons.value,
      };
      state.pageConfigProcessor.forEach(i => i(ret));
      return ret;
    });

    const refer = { state, pageConfig };

    provide(PROVIDE_NAME, refer);

    return refer;
  };

  const usePageConfig = (pageConfigProcessor: iMicroAppPageConfigProcessor): boolean => {
    const injection = inject(PROVIDE_NAME, null) as null | ReturnType<typeof useProvider>;
    if (!injection) {return false;}
    injection.state.pageConfigProcessor.push(pageConfigProcessor);
    onBeforeUnmount(() => {remove(injection.state.pageConfigProcessor, pageConfigProcessor);});
    return true;
  };
  const usePageTitle = (title: iMicroAppPageConfig['title']) => {return usePageConfig((pageConfig) => {pageConfig.title = title;});};

  return {
    useProvider,
    usePageConfig,
    usePageTitle,
  };
})();

export const usePageConfig = MicroAppPageConfig.usePageConfig;
export const usePageTitle = MicroAppPageConfig.usePageTitle;
